package com.happyfarmhelper.client;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;

import com.happyfarmhelper.ctrl.HappyCtrl;
import com.happyfarmhelper.utils.CommUtils;
import com.happyfarmhelper.vo.FarmlandStatus;
import com.happyfarmhelper.vo.Seed;
import com.happyfarmhelper.vo.User;


public class HappyFarmHelper extends JFrame implements ActionListener, KeyListener{
	
	private static final long serialVersionUID = -2591789814592110621L;
	
	private Log log = LogFactory.getLog(HappyFarmHelper.class);
	
	private HttpClient httpClient;
	private HttpGet httpGet;
	private HttpPost httpPost;
	
	private JTextField emailTfd, currentUserTfd, proxyAddressTfd, proxyPortTfd;
	private JPasswordField pwdPfd;
	private JButton loginBtn, logoutBtn, clearWeedBtn, sprayingBtn, previousBtn, nextBtn, harvestBtn, scarifyBtn, waterBtn, fertilizeBtn, refreshBtn, doEverythingBtn;
	private JList msgList;
	private DefaultListModel listModel;
	private JScrollPane msgPane;
	private JTable table;
	private JCheckBox isEnableProxy;
	private DefaultTableModel model;
	private final String[] headers = {"Land", "Plant Name", "Weed", "Worm", "Humidity", "Bug", "Growth Stage", "Mature Time"};
	
	private boolean isLoginSuccess = false;// 是否登录成功
	
	private int selectedIdx;
	private FarmlandStatus farmlandStatus;
	private List<FarmlandStatus> farmlandStatusList;
	private Map<String, Seed> seedsMap;
	private List<User> friendsList;
	private User owner;
	private User currentUser;
	private int currentFriendsIndex;
	private int ownerIndex;
	
	private MenuItem  exitItem;
	
	public HappyFarmHelper() {
		initComponents();
		initLayout();
	}
	
	private void initComponents() {
		listModel = new DefaultListModel();
		msgList = new JList(listModel);
		msgList.setAutoscrolls(true);
		msgList.setEnabled(false);
		msgList.setVisibleRowCount(5);
		
		emailTfd = new JTextField(20);
		emailTfd.addKeyListener(this);
		emailTfd.setText("@hotmail.com");
		
		currentUserTfd = new JTextField(20);
		currentUserTfd.setEnabled(false);
		
		pwdPfd = new JPasswordField();
		pwdPfd.addKeyListener(this);
		pwdPfd.setPreferredSize(emailTfd.getPreferredSize());
		
		loginBtn = new JButton("login");
		loginBtn.addActionListener(this);
		logoutBtn = new JButton("Logout");
		logoutBtn.addActionListener(this);
		
		clearWeedBtn = new JButton("ClearWeed");
		clearWeedBtn.addActionListener(this);
		
		sprayingBtn = new JButton("Spraying");
		sprayingBtn.addActionListener(this);
		
		previousBtn = new JButton("<");
		previousBtn.addActionListener(this);
		
		nextBtn = new JButton(">");
		nextBtn.addActionListener(this);
		
		refreshBtn = new JButton("Refresh");
		refreshBtn.addActionListener(this);
		
		harvestBtn = new JButton("Harvest");
		harvestBtn.addActionListener(this);
		
		scarifyBtn = new JButton("Scarify");
		scarifyBtn.addActionListener(this);
		
		waterBtn = new JButton("Water");
		waterBtn.addActionListener(this);
		
		fertilizeBtn = new JButton("Fertilize");
		fertilizeBtn.addActionListener(this);
		
		doEverythingBtn = new JButton("Do Everything");
		doEverythingBtn.addActionListener(this);
		
		isEnableProxy = new JCheckBox("Proxy?");
		isEnableProxy.setSelected(false);
		isEnableProxy.addActionListener(this);
		
		proxyAddressTfd = new JTextField(10);
		proxyAddressTfd.setEnabled(false);
		proxyPortTfd = new JTextField(3);
		proxyPortTfd.setEnabled(false);
		
		defaultStatus();
		initHttpComponents();
		initTable();
	}
	
	private void defaultStatus(){
		clearWeedBtn.setEnabled(isLoginSuccess);
		sprayingBtn.setEnabled(isLoginSuccess);
		previousBtn.setEnabled(isLoginSuccess);
		nextBtn.setEnabled(isLoginSuccess);
		harvestBtn.setEnabled(isLoginSuccess);
		scarifyBtn.setEnabled(isLoginSuccess);
		waterBtn.setEnabled(isLoginSuccess);
		fertilizeBtn.setEnabled(isLoginSuccess);
		refreshBtn.setEnabled(isLoginSuccess);
		doEverythingBtn.setEnabled(isLoginSuccess);
	}
	
	private void initHttpComponents() {
		BasicHttpParams httpParams = new BasicHttpParams();
		List<Header> headers = CommUtils.initHeaders();
		httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
		httpParams.setParameter(ClientPNames.DEFAULT_HEADERS, headers);
		SchemeRegistry schemeRegistry = new SchemeRegistry();  
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        
		ClientConnectionManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
		
		httpClient = new DefaultHttpClient(cm, httpParams);
		
		httpGet = new HttpGet();
		httpGet.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
		httpGet.getParams().setParameter("http.method.retry-handler", new DefaultHttpRequestRetryHandler());
		httpPost = new HttpPost();
		httpPost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
		httpPost.getParams().setParameter("http.method.retry-handler", new DefaultHttpRequestRetryHandler());
	}
	
	
	private void initLayout() {
		JPanel topPnl = new JPanel(new BorderLayout());

		JPanel conditionPnl = new JPanel(new GridBagLayout());
		conditionPnl.add(new JLabel("email"), new GridBagConstraints(0, 0, 1,
				1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
				new Insets(5, 5, 0, 5), 0, 0));
		conditionPnl.add(emailTfd, new GridBagConstraints(1, 0, 1, 1, 0.0, 1.0,
				GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5,
						0, 0, 5), 0, 0));
		conditionPnl.add(isEnableProxy, new GridBagConstraints(2, 0, 1,
				1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
				new Insets(5, 5, 0, 5), 0, 0));
		conditionPnl.add(proxyAddressTfd, new GridBagConstraints(3, 0, 1, 1, 0.0, 1.0,
				GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5,
						0, 0, 5), 0, 0));
		conditionPnl.add(proxyPortTfd, new GridBagConstraints(4, 0, 1, 1, 0.0, 1.0,
				GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5,
						0, 0, 5), 0, 0));
		conditionPnl.add(new JLabel("password"), new GridBagConstraints(0, 1,
				1, 1, 0.0, 0.0, GridBagConstraints.WEST,
				GridBagConstraints.NONE, new Insets(5, 5, 0, 5), 0, 0));
		conditionPnl.add(pwdPfd, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,
				GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5,
						0, 0, 5), 0, 0));
		conditionPnl.add(loginBtn, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0,
				GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5,
						0, 0, 5), 0, 0));
		conditionPnl.add(logoutBtn, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0,
				GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5,
						0, 0, 5), 0, 0));
		conditionPnl.add(previousBtn, new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0,
				GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5,
						0, 0, 5), 0, 0));
		conditionPnl.add(currentUserTfd, new GridBagConstraints(5, 1, 1, 1, 0.0, 0.0,
				GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5,
						0, 0, 5), 0, 0));
		conditionPnl.add(nextBtn, new GridBagConstraints(6, 1, 1, 1, 1.0, 0.0,
				GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5,
						0, 0, 5), 0, 0));
		JPanel btnPnl = new JPanel(new FlowLayout(FlowLayout.LEADING));
		btnPnl.add(clearWeedBtn);
		btnPnl.add(sprayingBtn);
		btnPnl.add(waterBtn);
		btnPnl.add(scarifyBtn);
		btnPnl.add(fertilizeBtn);
		btnPnl.add(harvestBtn);
		btnPnl.add(refreshBtn);
		btnPnl.add(doEverythingBtn);
		topPnl.add(conditionPnl, BorderLayout.CENTER);
		topPnl.add(btnPnl, BorderLayout.SOUTH);
		
		
		JScrollPane scollPane = new JScrollPane(table);
		
		msgPane = new JScrollPane(msgList);
//		msgPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener(){
//			public void adjustmentValueChanged(AdjustmentEvent e) {
//				if(!e.getValueIsAdjusting() && e.getAdjustmentType() == AdjustmentEvent.TRACK){
//					msgPane.getVerticalScrollBar().setValue(msgPane.getVerticalScrollBar().getMaximum() - msgPane.getVerticalScrollBar().getModel().getExtent());
//				}
//			}
//		});
		
		JPanel mainPnl = new JPanel(new BorderLayout());
		mainPnl.add(topPnl, BorderLayout.NORTH);
		mainPnl.add(scollPane, BorderLayout.CENTER);
		mainPnl.add(msgPane, BorderLayout.SOUTH);
		
		
		this.getContentPane().add(mainPnl);
		this.setPreferredSize(new Dimension(900, 600));
		this.pack();
//		this.setVisible(true);
//		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(false);
		this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		if(SystemTray.isSupported()) {
			SystemTray systemTray = SystemTray.getSystemTray();
			
			PopupMenu popuMenu = new PopupMenu();
			exitItem = new MenuItem("Exit");
			exitItem.addActionListener(this);
            popuMenu.add(exitItem);
            
			Image icon = new ImageIcon(HappyFarmHelper.class.getClassLoader().getResource("resources/java.jpg")).getImage();
			TrayIcon trayIcon = new TrayIcon(icon,"TrayIcon", popuMenu);
			try {
				systemTray.add(trayIcon);
				this.addWindowListener(new WindowAdapter(){
					public void windowDeiconified(WindowEvent e) {
						dispose();
						setVisible(false);
					}
				});
				trayIcon.addMouseListener(new MouseAdapter(){
					public void mouseClicked(MouseEvent e) {
						if(e.getClickCount() == 2) {//双击托盘窗口再现
							if(isVisible()){
								dispose();
								setVisible(false);
							} else {
								setExtendedState(JFrame.NORMAL);//状态
		                        setVisible(true);
							}
							 
                    	}
					}
				});
			} catch (AWTException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void initTable(){
		model = new DefaultTableModel(){
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int column) {
		        return false;
		    }
		};
		model.setColumnIdentifiers(headers);
		table = new JTable(model);
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
			//当鼠标选中某行时,会触发两次
			//一次 鼠标按下
			//一次 鼠标释放
			public void valueChanged(ListSelectionEvent e) {
				if(e.getValueIsAdjusting()){//鼠标按下
					selectedIdx = table.getSelectedRow();
					farmlandStatus = farmlandStatusList.get(selectedIdx);
					setButtonStatus();
				}
			}
			
		});
		table.setRowHeight(25);
		table.setColumnSelectionAllowed(false);
		table.setRowSelectionAllowed(true);
		table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
	}
	
	private void setButtonStatus() {
		if(farmlandStatus.getWeed() > 0) {
			clearWeedBtn.setEnabled(true);
		} else {
			clearWeedBtn.setEnabled(false);
		}
		
		if((farmlandStatus.getWorm() + farmlandStatus.getBug()) > 0) {
			sprayingBtn.setEnabled(true);
		} else {
			sprayingBtn.setEnabled(false);
		}
		
		if(farmlandStatus.getGrowthStage() == 6 && !farmlandStatus.isScrounged()) {
			harvestBtn.setEnabled(true);
		} else {
			harvestBtn.setEnabled(false);
		}
		
		if(farmlandStatus.getGrowthStage() == 7) {
			scarifyBtn.setEnabled(true);
		} else {
			scarifyBtn.setEnabled(false);
		}
		
		if(farmlandStatus.getHumidity() == 0) {
			waterBtn.setEnabled(true);
		} else {
			waterBtn.setEnabled(false);
		}
	}
	public static void main(String[] args) {
		HappyFarmHelper happyFarmhelper = new HappyFarmHelper();
		happyFarmhelper.setTitle("Happyfarm Helper");
	}


	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == loginBtn) {
			makeLogin();
		} else if(e.getSource() == exitItem) {
			System.exit(0);
		} else if(e.getSource() == clearWeedBtn) {
			clearWeed(farmlandStatus.getWeed(), selectedIdx);
			refresh();
			fillTable(selectedIdx);
		} else if(e.getSource() == sprayingBtn) {
			spraying(farmlandStatus.getWorm() + (farmlandStatus.getBug() > 0 ? 1 : 0), selectedIdx);
			refresh();
			fillTable(selectedIdx);
		} else if(e.getSource() == waterBtn) {
			water(selectedIdx);
			refresh();
			fillTable(selectedIdx);
		} else if(e.getSource() == fertilizeBtn) {
			fertilize(selectedIdx);
			refresh();
			fillTable(selectedIdx);
		} else if(e.getSource() == scarifyBtn) {
			scarify(selectedIdx);
			refresh();
			fillTable(selectedIdx);
		} else if(e.getSource() == harvestBtn){
			harvest(selectedIdx);
			if(currentUser.getUserId() == owner.getUserId()){
				scarify(selectedIdx);
			}
			refresh();
			fillTable(selectedIdx);
		} else if(e.getSource() == previousBtn) {
			changeFriends(false);
		} else if(e.getSource() == nextBtn) {
			changeFriends(true);
		} else if(e.getSource() == refreshBtn){
			refresh();
			fillTable(-1);
		} else if(e.getSource() == doEverythingBtn) {
			doEverything();
		} else if(e.getSource() == logoutBtn){
			logout();
		}
	}
	
	@SuppressWarnings("unchecked")
	private void makeLogin() {
		defaultStatus();
		try {
			if(HappyCtrl.getInstance().loginToRenren(httpClient, httpGet, httpPost, emailTfd.getText().trim(), new String(pwdPfd.getPassword()))) {
				isLoginSuccess = true;
				addMessage("Login Success!");
				defaultStatus();
				Map<String, Object> farmlandMap = HappyCtrl.getInstance().loginToHappyfarm(httpClient, httpGet);
				farmlandStatusList = (List<FarmlandStatus>)farmlandMap.get("farmlandStatusList");
				owner = (User)farmlandMap.get("owner");
				currentUser = owner;
				currentUserTfd.setText(currentUser.getUserId() + "-" + currentUser.getUserName());
				friendsList = HappyCtrl.getInstance().getFriends(httpClient, httpPost);
				if(friendsList == null || friendsList.size() == 0) {
					addMessage("Load Friends Failed!");
					friendsList = new ArrayList<User>();
					friendsList.add(owner);
				}
				ownerIndex = friendsList.indexOf(owner);
				currentFriendsIndex = ownerIndex;
				
				seedsMap = HappyCtrl.getInstance().getSeedInfo(httpClient, httpPost);
			} else {
				addMessage("Login Error! Try Again!");
				log.info("Login Error! Try Again!");
			}
		} catch (ClientProtocolException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} catch (IOException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} finally {
			httpGet.abort();
			httpPost.abort();
		}
		
		fillTable(-1);
		Timer timer = new Timer();
		timer.schedule(new TimerTask(){
			@Override
			public void run() {
				if(isLoginSuccess){
					doEverything();
				}
			}
		}, 1500000,1500000);
	}
	
	private void fillTable(int place){
		
		if(place == -1){
			model.setRowCount(0);
			selectedIdx = 0;
			farmlandStatus = farmlandStatusList.get(0);
		}
		else {
			selectedIdx = place;
			farmlandStatus = farmlandStatusList.get(place);
		}
		int count = (place == -1 ? farmlandStatusList.size() : 1);
		for(int i = 0; i < count; i++) {
			FarmlandStatus farmlandStatus = farmlandStatusList.get(count == 1 ? place : i);
			
			Vector<Object> vector = new Vector<Object>();
			vector.add(0, count == 1 ? place : i);
			int growthCycle = 0;
			if(seedsMap.containsKey(String.valueOf(farmlandStatus.getPlantId()))){
				vector.add(1, seedsMap.get(String.valueOf(farmlandStatus.getPlantId())).getSeedName());
				growthCycle = seedsMap.get(String.valueOf(farmlandStatus.getPlantId())).getGrowthCycle();
			}
			else {
				vector.add(1, "Unknow");
				growthCycle = 3600000;
			}
			vector.add(2, farmlandStatus.getWeed());
			vector.add(3, farmlandStatus.getWorm());
			vector.add(4, (farmlandStatus.getHumidity() == 0) ? "true" : "false");
			vector.add(5, farmlandStatus.getBug());
			String status = (farmlandStatus.getGrowthStage() == 6) ? "Matured" : (farmlandStatus.getGrowthStage() == 7) ? "Withered" : "Not Matured";
			vector.add(6, status);
			String matureTime = "";
			if(farmlandStatus.getGrowthStage() == 0 || farmlandStatus.getGrowthStage() == 6 || farmlandStatus.getGrowthStage() == 7){
				matureTime = "-";
			} 
			else {
				long tempTime = farmlandStatus.getPlantTime() + growthCycle;
				long now = Calendar.getInstance().getTimeInMillis() / 1000;
				long intervalTime = tempTime - now;
				matureTime = CommUtils.getInterval(intervalTime);
			}
			vector.add(7, matureTime);
			if(place == -1){
				model.addRow(vector);
			} else {
				for(int j = 0; j < vector.size(); j++){
					model.setValueAt(vector.get(j), place, j);
				}
				table.validate();
				table.repaint();
			}
		}
		setButtonStatus();
	}
	
	private void changeFriends(boolean isClockwise) {
		if(isClockwise) {
			currentFriendsIndex = (currentFriendsIndex == friendsList.size() - 1) ? 0 : (currentFriendsIndex + 1);
		} else {
			currentFriendsIndex = (currentFriendsIndex == 0) ? (friendsList.size() - 1) : (currentFriendsIndex - 1);
		}
		currentUser = friendsList.get(currentFriendsIndex);
		if(currentUser.getUserId() == owner.getUserId()){
        	harvestBtn.setText("Harvest");
        	fertilizeBtn.setEnabled(true);
        } else {
        	harvestBtn.setText("Scrounge");
        	fertilizeBtn.setEnabled(false);
        }
        currentUserTfd.setText(friendsList.get(currentFriendsIndex).getUserId() + "-" + friendsList.get(currentFriendsIndex).getUserName());
        refresh();
        fillTable(-1);
	}
	
	private void refresh() {
		String userId = currentUser.getUserId() == owner.getUserId() ? "0" : String.valueOf(currentUser.getUserId());
		try {
			farmlandStatusList = HappyCtrl.getInstance().refresh(httpClient, httpPost, userId);
		} catch (ClientProtocolException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} catch (IOException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} finally {
			httpPost.abort();
		}
	}
	/**
	 * 除草
	 * @param quantityOfWeed
	 * @param place
	 */
	private void clearWeed(int quantityOfWeed, int place) {
		StringBuffer msgBuffer = new StringBuffer();
		msgBuffer.append(currentUser.toString()).append(":");
		try {
			String msg = HappyCtrl.getInstance().clearWeed(httpClient, httpPost, String.valueOf(currentUser.getUserId()), quantityOfWeed, place);
			String message = msgBuffer.append(msg).toString();
			addMessage(message);
			log.info(message);
		} catch (ClientProtocolException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} catch (IOException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} finally {
			httpPost.abort();
		}
	}
	/**
	 * 除虫
	 * @param quantityOfWorm
	 * @param place
	 */
	private void spraying(int quantityOfWorm, int place) {
		StringBuffer msgBuffer = new StringBuffer();
		msgBuffer.append(currentUser.toString()).append(":");
		try {
			String msg = HappyCtrl.getInstance().spraying(httpClient, httpPost, String.valueOf(currentUser.getUserId()), quantityOfWorm, place);
			String message = msgBuffer.append(msg).toString();
			addMessage(message);
			log.info(message);
		} catch (ClientProtocolException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} catch (IOException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} finally {
			httpPost.abort();
		}
	}
	/**
	 * 浇水
	 * @param place
	 */
	private void water(int place) {
		StringBuffer msgBuffer = new StringBuffer();
		msgBuffer.append(currentUser.toString()).append(":");
		try {
			String msg = HappyCtrl.getInstance().water(httpClient, httpPost, String.valueOf(currentUser.getUserId()), place);
			String message = msgBuffer.append(msg).toString();
			addMessage(message);
			log.info(message);
		} catch (ClientProtocolException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} catch (IOException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} finally {
			httpPost.abort();
		}
	}
	/**
	 * 施肥
	 * @param place
	 */
	private void fertilize(int place) {
		StringBuffer msgBuffer = new StringBuffer();
		msgBuffer.append(currentUser.toString()).append(":");
		try {
			String msg = HappyCtrl.getInstance().fertilize(httpClient, httpPost, String.valueOf(currentUser.getUserId()), place);
			String message = msgBuffer.append(msg).toString();
			addMessage(message);
			log.info(message);
		} catch (ClientProtocolException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} catch (IOException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} finally {
			httpPost.abort();
		}
		
	}
	/**
	 * 翻地
	 * @param place
	 */
	private void scarify(int place) {
		StringBuffer msgBuffer = new StringBuffer();
		msgBuffer.append(currentUser.toString()).append(":");
		try {
			String msg = HappyCtrl.getInstance().scarify(httpClient, httpPost, String.valueOf(currentUser.getUserId()), place);
			String message = msgBuffer.append(msg).toString();
			addMessage(message);
			log.info(message);
		} catch (ClientProtocolException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} catch (IOException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} finally {
			httpPost.abort();
		}
	}
	/**
	 * 偷菜
	 * @param place
	 */
	private void harvest(int place){
		StringBuffer msgBuffer = new StringBuffer();
		msgBuffer.append(currentUser.toString()).append(":");
		String preUrl = (currentUser.getUserId() == owner.getUserId()) ? "http://xn.hf.fminutes.com/api.php?mod=farmlandstatus&act=harvest&farmKey=" : "http://xn.hf.fminutes.com/api.php?mod=farmlandstatus&act=scrounge&farmKey=";
		try {
			String msg = HappyCtrl.getInstance().harvest(httpClient, httpPost, String.valueOf(currentUser.getUserId()), preUrl, place);
			String message = msgBuffer.append(msg).toString();
			addMessage(message);
			log.info(message);
		} catch (ClientProtocolException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} catch (IOException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} finally {
			httpPost.abort();
		}
	}
	
	
	
	private void doEverything(){
		for(User friend : friendsList) {
			if(friend.getUserId() != owner.getUserId()){
				currentUser = friend;
				refresh();
				for(int i = 0; i < farmlandStatusList.size(); i ++) {
					farmlandStatus = farmlandStatusList.get(i);
					if(farmlandStatus.getGrowthStage() == 6 && !farmlandStatus.isScrounged() && farmlandStatus.isCanScrounge()){
						harvest(i);
					}
					if(farmlandStatus.getWeed() > 0) {
						clearWeed(farmlandStatus.getWeed(), i);
					}
					if((farmlandStatus.getWorm() + farmlandStatus.getBug()) > 0) {
						spraying(farmlandStatus.getWorm() + (farmlandStatus.getBug() > 0 ? 1 : 0), i);
					}
					if(farmlandStatus.getHumidity() == 0){
						water(i);
					}
				}
			}
		}
		currentUser = owner;
		currentUserTfd.setText(currentUser.getUserId() + "-" + currentUser.getUserName());
		currentFriendsIndex = ownerIndex;
		refresh();
		
		for(int i = 0; i < farmlandStatusList.size(); i ++) {
			farmlandStatus = farmlandStatusList.get(i);
			if(farmlandStatus.getGrowthStage() != 0 && farmlandStatus.getGrowthStage() != 6 && farmlandStatus.getGrowthStage() != 7){
				long plantTime = farmlandStatus.getPlantTime();
				long growthCycle = 0;
				if(seedsMap.containsKey(String.valueOf(farmlandStatus.getPlantId()))){
					growthCycle = seedsMap.get(String.valueOf(farmlandStatus.getPlantId())).getGrowthCycle();
				}
				double now = Math.ceil(Calendar.getInstance().getTimeInMillis() / 1000);
				double tempTime = plantTime + growthCycle - now;
				if(growthCycle != 0 && tempTime < 3600) {
					fertilize(i);
				}
				
				if(farmlandStatus.getWeed() > 0) {
					clearWeed(farmlandStatus.getWeed(), i);
				}
				if((farmlandStatus.getWorm() + farmlandStatus.getBug()) > 0) {
					spraying(farmlandStatus.getWorm() + (farmlandStatus.getBug() > 0 ? 1 : 0), i);
				}
				if(farmlandStatus.getHumidity() == 0) {
					water(i);
				}
			}
		}
		refresh();
		for(int i = 0; i < farmlandStatusList.size(); i ++) {
			farmlandStatus = farmlandStatusList.get(i);
			if(farmlandStatus.getGrowthStage() == 6){
				harvest(i);
			}
		}
		refresh();
		for(int i = 0; i < farmlandStatusList.size(); i ++) {
			farmlandStatus = farmlandStatusList.get(i);
			if(farmlandStatus.getGrowthStage() == 7){
				scarify(i);
			}
		}
		refresh();
		fillTable(-1);
	}
	
	private void logout() {
		try {
			HappyCtrl.getInstance().logout(httpClient, httpGet);
			addMessage("Logout Finished!");
			log.info("Logout Finished!");
		} catch (ClientProtocolException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} catch (IOException e) {
			addMessage(e.getMessage());
			log.info(e.getMessage());
		} finally {
			httpGet.abort();
		}
	}
	
	private void addMessage(final String msg) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				listModel.addElement(CommUtils.showCalendar()  + " " + msg);
				msgPane.getVerticalScrollBar().setValue(msgPane.getVerticalScrollBar().getMaximum());
			}
		});
	}

	@Override
	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyReleased(KeyEvent e) {
		if(pwdPfd.isFocusOwner() && e.getKeyCode() == KeyEvent.VK_ENTER) {
			makeLogin();
		}
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	
}
